package server;

import pojo.Context;
import pojo.Host;
import pojo.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Host host;

    public RequestProcessor(Socket socket, Host host) {
        this.socket = socket;
        this.host = host;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            List<Context> contextList = host.getContextList();
            for (Context context : contextList) {
                if (request.getHost().equals(context.getHost())) {
                    List<Wrapper> wrapperList = context.getWrapperList();
                    boolean flag = false;
                    for (Wrapper wrapper : wrapperList) {
                        if (request.getUrl().equals(wrapper.getUrlPattern())) {
                            flag = true;
                            wrapper.getServlet().service(request,response);
                        }
                    }
                    if (!flag) {
                        response.outputHtml(request.getUrl());
                    }
                }
            }
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
